import datetime

from sqlalchemy import and_, or_

from cc_flask.exception import ErrCode, NotFound
from cc_flask.request_handle import required_args, RV, ResponseBase, RRManage
from . import models
from .models import User, UserGroup

session = models.db.session
from sqlalchemy.orm import class_mapper
from sqlalchemy.inspection import inspect


def health():
    """ 用于Docker健康检查，如果删除该方法，请修改docker-compose.yml文件 """
    return ResponseBase.success()


@required_args(username__="用户名", email__='邮箱', phone="手机号")
def add_user(r):
    """ 添加用户 """
    # print(r.to_dict)  # 获取所有@required_args装饰器中定义的参数，前端不传时为None
    # print(r.req_args)  # 获取前端传参 并且 @required_args已定义的参数。如果前端不传，或者装饰器中没有定义，都不获取
    # 通过r.dict_data 接收所有定义的参数
    user = User(**r.to_dict)
    session.add(user)
    session.commit()

    return r.response_success()


@required_args(id__="用户id", username__="用户名", email__='邮箱', phone="手机号")
def modify_user(r):
    """ 修改用户 """
    user = User.query.filter_by(id=r.id)
    if not user.first():
        return r.response_error(ErrCode.NOT_FOUND, "对象不存在或已被删除")

    update_dict = {}
    for k, v in r.req_args.items():
        update_dict[getattr(User, k)] = v

    user.update(update_dict)
    session.commit()
    return r.response_success()


@required_args(search="搜索")
def user_list(r):
    user = User.query.options(models.db.joinedload(User.group))

    if r.search:
        user = user.filter(User.username.ilike(r.search))

    return r.response_success([i.get_detail() for i in user.all()])


@required_args(id__="用户id")
def delete_user(r):
    """ 删除用户 """

    user = User.query.filter_by(id=r.id)
    if not user.first():
        raise NotFound("找不到对象")

    user.delete()
    session.commit()
    return r.response_success()
